<template>
  <el-dialog
    :title="dialogtitle"
    :visible="dialogvisible"
    width="500px"
    @close="closeDialog"
  >
    <el-form ref="form" :model="roleInfo" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleInfo.name" placeholder="1~50个字符" style="width:80%" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleInfo.description" placeholder="1~50个字符" style="width:80%" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="clickSubmit">确 定</el-button>
      <el-button size="small" @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { additionRole, editRole, getRoleInfo } from '@/api/role'
export default {
  props: {
    dialogtitle: {
      default: '',
      type: String
    },
    dialogvisible: {
      type: Boolean
    }
  },
  data() {
    return {
      roleInfo: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    closeDialog() {
      this.$emit('close-dialog')
      this.$refs.form.resetFields()
      this.roleInfo = {
        name: '',
        description: ''
      }
    },
    clickSubmit() {
      // 兜底校验
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.dialogtitle === '新增角色') {
            await additionRole(this.roleInfo)
          } else {
            await editRole(this.roleInfo)
          }
          this.$message.success(this.dialogtitle + '成功')
          this.$emit('click-submit')
          this.closeDialog()
        }
      })
    },
    async getRoleDetail(id) {
      const res = await getRoleInfo(id)
      this.roleInfo = res
    }
  }

}
</script>

<style lang='css' scoped></style>
